package tech.summerly.weather.component.adapter

import android.support.v4.app.FragmentActivity
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.item_daily_forecast.view.*
import kotlinx.android.synthetic.main.item_daily_nav.view.*
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
import tech.summerly.weather.R
import tech.summerly.weather.component.fragments.DailyTrendFragment
import tech.summerly.weather.data.bean.DailyForecast
import tech.summerly.weather.data.remote.CaiYunService
import tech.summerly.weather.util.*
import java.util.*

class DailyForecastAdapterVertical : RecyclerView.Adapter<ViewHolder>() {

    companion object {
        private const val TYPE_NORMAL = 0
        private const val TYPE_NAV = 1
    }

    private var daily: DailyForecast? = null

    fun setDailyForecast(dailyForecast: DailyForecast) {
        val old = daily
        daily = dailyForecast
        if (old == null) {
            notifyItemRangeInserted(0, itemCount)
            return
        }
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return when (viewType) {
            TYPE_NORMAL -> DailyItemViewHolder(ViewHolder.createView(R.layout.item_daily_forecast, parent))
            TYPE_NAV -> DailyNavViewHolder(ViewHolder.createView(R.layout.item_daily_nav, parent))
            else -> throw IllegalStateException()
        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == itemCount - 1) {
            TYPE_NAV
        } else {
            TYPE_NORMAL
        }
    }

    override fun getItemCount(): Int = if (daily == null) 0 else 4

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val daily = daily ?: return
        when (getItemViewType(position)) {
            TYPE_NORMAL -> {
                holder as DailyItemViewHolder
                val temperature = daily.temperature[position]
                val calendar = temperature.date.formatDate()
                val day = if (calendar.isToday()) {
                    string(R.string.today)
                } else {
                    string(R.string.month_day_template, calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH))
                }
                val skyCon = daily.skycon[position].value
                val temperatureText = string(R.string.template_celsius,
                        "%s/%s".format(temperature.max.toIntString(), temperature.min.toIntString()))
                val aqi = Aqi.from(daily.aqi[position].avg.toInt())
                holder.set(day, skyCon, temperatureText, aqi.localString())
            }
            TYPE_NAV -> {
                holder as DailyNavViewHolder
                holder.set(string(R.string.template_daily_item_nav, daily.aqi.size))
                holder.itemView.setOnClickListener {
                    val context = it.context as FragmentActivity
                    context.supportFragmentManager.inTransaction {
                        val fragment = DailyTrendFragment()
                        add(android.R.id.content, fragment, DailyTrendFragment.TAG)
                        addToBackStack(DailyTrendFragment.TAG)
                        launch(UI) {
                            while (fragment.view == null) {
                                delay(10)
                            }
                            fragment.setDailyForecast(daily)
                        }
                    }
                }
            }
        }
    }

    class DailyItemViewHolder(itemView: View) : ViewHolder(itemView) {


        fun set(day: String, skyCon: String, temperature: String, aqi: String) = with(itemView) {
            val skyConIcon = CaiYunService.SkyCon.getSkyIcon(skyCon)
            textDay.text = day
            imageSky.setImageResource(skyConIcon)
            textSky.text = CaiYunService.SkyCon.getSkyConLocalString(skyCon)
            textAqi.text = aqi
            textTemperature.text = temperature
        }
    }

    class DailyNavViewHolder(itemView: View) : ViewHolder(itemView) {

        fun set(text: String) = with(itemView) {
            textButton.setText(text)
        }
    }
}